const gulp = require('gulp');
const del = require('del');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync');
const reload = browserSync.reload;
const plumber = require('gulp-plumber');
const notify = require('gulp-notify');
const cleanCSS = require('gulp-clean-css');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
/* Setting */
var TEACHER = {
	DIST: {
		src: 'WebRoot/teacher/resource/',
		css: function() {
			return this.src + 'css/';
		},
		script: function() {
			return this.src + 'script/';
		},
		getSrc: function() {
			return this.src;
		}
	},
	APP: {
		src: 'WebRoot/teacher/resource/',
		scss: function() {
			return this.src + 'scss/';
		},
		script: function() {
			return this.src + 'script/';
		}
	}
}
/* Task */
// 1.清空
gulp.task('clean', function(cb) {
    del([TEACHER.DIST.css()+ '**/*'], cb);
});

// 2.编译scss
gulp.task('scss', function() {
	return gulp.src([TEACHER.APP.scss() + '**/*.scss'])
		.pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(sass())
        .pipe(autoprefixer(
            {
                browsers: ['last 2 version', '> 5%', 'safari > 5','chrome > 35', 'ff > 10', 'opera > 10', 'ie > 6'],
                cascade: false
            }
        ))
        .pipe(cleanCSS())
        .pipe(gulp.dest(TEACHER.DIST.css()))
        .pipe(reload({stream: true}));
});

// 3.合并公用js
gulp.task('script', function() {
	return gulp.src([
			TEACHER.APP.script()+'base/api.js',
			TEACHER.APP.script()+'app.js',
			TEACHER.APP.script()+'service/**/*.js',
			TEACHER.APP.script()+'filter/**/*.js',
			TEACHER.APP.script()+'directive/**/*.js'
		])
		.pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
		// .pipe(uglify())
       	.pipe(concat('main.js'))
       	.pipe(gulp.dest(TEACHER.DIST.script()+'dist/'))
       	.pipe(reload({stream: true}))
});

// 4.合并controller
gulp.task('controller', function() {
	return gulp.src([
		TEACHER.APP.script()+'controller/**/*.js'
	])
	.pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
	// .pipe(uglify())
   	.pipe(concat('controller.js'))
   	.pipe(gulp.dest(TEACHER.DIST.script()+'dist/'))
   	.pipe(reload({stream: true}))
})


//browser-sync，自动刷新页面
gulp.task('browser-sync', ['scss', 'script', 'controller'], function() {
    browserSync.init({
        server: {
            baseDir: ['WebRoot/']
        }
    });
    gulp.watch([TEACHER.APP.scss()+ '**/*.scss'], ['scss']);
    gulp.watch([TEACHER.APP.script()+ '**/*.js'], ['script', 'controller']);
});


gulp.task('default', ['browser-sync'], function() {

});